/**
 * Copyright (2024, ) Institute of Software, Chinese Academy of Sciences
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *limitations under the License.
 */
package cn.ac.iscas.targets.rbd;

import java.util.List;
import java.util.logging.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.ac.iscas.targets.RDBTarget;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.NoResultException;
import jakarta.persistence.Query;

/**
 * Http的配置文件，又可细分为多种
 * - username和password
 * - token
 * - cookie
 * - cert
 * 
 * @author wuheng@iscas.ac.cn
 * @since 1.0.0
 * 
 */
public class PostgresTarget extends RDBTarget {

	/**
	 * 日志
	 */
	static final Logger m_logger = Logger.getLogger(PostgresTarget.class.getName());
	
	/**
	 * 默认postgres地址
	 */
	static final String DEFAULT_JDBCURL    = "jdbc:postgresql://kube-database.kube-iscas:5432/kubestack?useUnicode=true&characterEncoding=UTF8&autoReconnect=true&&serverTimezone=Asia/Shang";
	
	/**
	 * 默认用户名
	 */
	static final String DEFAULT_USERNAME   = "postgres";
	
	/**
	 * 默认密码
	 */
	static final String DEFAULT_PASSWORD   = "onceas";
	
	/**
	 * 默认驱动
	 */
	static final String DEFAULT_JDBCDRIVER = "org.postgresql.Driver";
	
	
	/**
	 * 默认驱动
	 */
	static final String DEFAULT_POOLSIZE   = "2";
	
	public PostgresTarget(String jdbcUrl, String username, String password, String jdbcDriver, String poolSize) {
		super(jdbcUrl, username, password, jdbcDriver, poolSize);
	}

	/**
	 * @param sql        SQL
	 * @return           查询结果
	 */
	public Object execWithSingleResult(String sql) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			Query query = entityManager.createNativeQuery(sql);
			Object singleResult = query.getSingleResult();
			transaction.commit();
			return singleResult;
		} catch (Exception ex) {
			m_logger.warning("执行错误" + ex);
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		return null;
	}
	
	/**
	 * @param sql        SQL
	 * @return           查询结果
	 */
	public long count(String sql) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			Query query = entityManager.createNativeQuery(sql);
			long singleResult = (long) query.getSingleResult();
			transaction.commit();
			return singleResult;
		} catch (NoResultException ex) {
			m_logger.warning("没有查询到任何结果");
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		return -1;
	}
	
	/**
	 * @param sql        SQL
	 * @return           查询结果
	 */
	public JsonNode get(String sql) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			Query query = entityManager.createNativeQuery(sql);
			Object singleResult = query.getSingleResult();
			transaction.commit();
			return new ObjectMapper().readTree(singleResult.toString());
		} catch (JsonProcessingException e) {
			m_logger.warning("结果转JSON失败" + e);
		} catch (NoResultException ex) {
			m_logger.warning("没有查询到任何结果" + ex);
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		return null;
	}
	
	
	/**
	 * @param sql        SQL
	 * @return           查询结果
	 */
	public JsonNode list(String sql) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			Query query = entityManager.createNativeQuery(sql);
			List<?> mutipleResults = query.getResultList();
			transaction.commit();
			return new ObjectMapper().readTree(mutipleResults.toString());
		} catch (JsonProcessingException e) {
		} catch (NoResultException ex) {
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		return null;
	}
	
	/**
	 * @param sql SQL
	 * @return
	 */
	public boolean execWithoutResult(String sql) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			entityManager.createNativeQuery(sql).executeUpdate();
			transaction.commit();
			return true;
		} catch (Exception ex) {
			return false;
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
	}
	
	
}
